<template>
  <div class="mine-detail-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="账号设置"
      left-arrow
      @click-left="goBack"
      :style="{ backgroundColor: '#FFD847' }"
    />
    <!-- 头像 -->
    <van-cell class="avatar-cell" title="头像" is-link @click="handleAvatarClick">
      <template #value>
        <van-image
          class="avatar-image"
          :src="userInfo.avatar"
          round
          fit="cover"
        />
      </template>
    </van-cell>
    <!-- ID（不可修改） -->
    <van-cell title="ID">
      <template #value>
        <span class="readonly-text">{{ userInfo.id }}</span>
      </template>
    </van-cell>
    <!-- 用户名 -->
     <van-cell title="用户名" is-link :value="userInfo.username || '未填写'" @click="showUsernameDialog" />
    <!-- 昵称 -->
    <van-cell title="昵称" is-link :value="userInfo.nickname || '未填写'" @click="showNicknameDialog" />
    <!-- 邮箱 -->
    <van-cell title="邮箱" is-link :value="userInfo.email || '未设置'" @click="showEmailDialog" />
    <!-- 性别 -->
    <van-cell title="性别" is-link :value="userInfo.gender || '未填写'" @click="showGenderPicker" />
    <!-- 手机号 -->
    <van-cell title="手机号">
      <template #value>
        <span class="readonly-text">{{ userInfo.mobile || '未绑定' }}</span>
      </template>
    </van-cell>
    <!-- 修改密码 -->
    <van-cell icon="lock" title="修改密码" is-link @click="showPasswordDialog" />
    <!-- 功能列表 -->
    <div class="function-list">
      <van-cell icon="description" title="个人信息浏览及导出" is-link @click="handleExportInfo" />
      <van-cell icon="delete-o" title="申请注销账号" is-link @click="handleDeleteAccount">
        <template #label>
          <span class="warning-text">注销后账号无法找回</span>
        </template>
      </van-cell>
    </div>
    <!-- 用户名修改弹窗 -->
     <van-dialog 
      v-model:show="usernameDialogVisible" 
      title="用户名"
      show-cancel-button
      @confirm="handleUsernameConfirm"
    >
      <van-field
        v-model="tempUsername"
        placeholder="请输入2~10位用户名"
        maxlength="10"
      />
    </van-dialog>
    <!-- 昵称修改弹窗 -->
    <van-dialog 
      v-model:show="nicknameDialogVisible" 
      title="昵称"
      show-cancel-button
      @confirm="handleNicknameConfirm"
    >
      <van-field
        v-model="tempNickname"
        placeholder="请输入2~10位昵称"
        maxlength="10"
      />
    </van-dialog>
    <!-- 邮箱修改弹窗 -->
    <van-dialog 
      v-model:show="emailDialogVisible" 
      title="邮箱"
      show-cancel-button
      @confirm="handleEmailConfirm"
    >
      <van-field
        v-model="tempEmail"
        placeholder="请输入邮箱地址"
        type="email"
      />
    </van-dialog>
    <!-- 性别选择器 -->
    <van-action-sheet v-model:show="genderPickerVisible" :actions="genderActions" @select="onGenderSelect" />

    <!-- 修改密码弹窗 -->
    <van-dialog 
      v-model:show="passwordDialogVisible" 
      title="修改密码"
      show-cancel-button
      :before-close="handlePasswordDialogClose"
      @confirm="handleChangePassword"
      :confirm-button-loading="passwordLoading"
    >
      <div class="password-dialog-content">
        <van-field
          v-model="newPassword"
          type="password"
          label="新密码"
          placeholder="请输入新密码（至少6位）"
        />
        <van-field
          v-model="confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请再次输入新密码"
        />
      </div>
    </van-dialog>
    <!-- 头像选择器 -->
    <van-action-sheet v-model:show="avatarPickerVisible" :actions="avatarActions" @select="onAvatarSelect" />
    <!-- 图片上传（隐藏） -->
    <input 
      ref="fileInput" 
      type="file" 
      accept="image/*" 
      style="display: none" 
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUser, updateUser, resetAccount, uploadImageApi } from '@/api'
import { getToken, removeToken } from '@/utils/token'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const fileInput = ref(null)

// 用户信息
const userInfo = ref({
  id: '',
  username: '',
  nickname: '',
  email: '',
  gender: '',
  mobile: '',
  avatar: ''
})


// 密码相关
const newPassword = ref('')
const confirmPassword = ref('')
const passwordLoading = ref(false)

// 弹窗显示状态
const usernameDialogVisible = ref(false)
const nicknameDialogVisible = ref(false)
const emailDialogVisible = ref(false)
const genderPickerVisible = ref(false)
const avatarPickerVisible = ref(false)
const passwordDialogVisible = ref(false)

// 临时数据
const tempUsername = ref('')
const tempNickname = ref('')
const tempEmail = ref('')

// 性别选项
const genderActions = [
  { name: '男' },
  { name: '女' },
  { name: '取消' }
]

// 头像选项
const avatarActions = [
  { name: '拍照' },
  { name: '从相册中选择' },
  { name: '取消' }
]

// 获取用户信息
const fetchUserInfo = async () => {
  const token = getToken()
  if (!token) {
    showToast('请先登录')
    router.push({ name: 'login' })
    return
  }
  try {
    const data = await getUser()
    console.log('用户信息:', data)
    
    if (data.User) {
      userInfo.value = {
        id: data.User.id || '',
        username: data.User.username || '',
        nickname: data.User.nickname || '',
        email: data.User.email || '',
        gender: data.User.gender || '',
        mobile: data.User.mobile || '',
        avatar: data.User.avatar || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    showToast('获取信息失败')
  }
}

// 显示用户名修改弹窗
const showUsernameDialog = () => {
  tempUsername.value = userInfo.value.username
  usernameDialogVisible.value = true
}

// 确认修改用户名
const handleUsernameConfirm = async () => { 
  if (!tempUsername.value || tempUsername.value.trim() === '') {
    showToast('用户名不能为空')
    return
  }
  if (tempUsername.value.length < 2 || tempUsername.value.length > 10) {
    showToast('用户名长度为2-10位')
    return
  }
  try {
    await updateUser({ username: tempUsername.value })
    userInfo.value.username = tempUsername.value
    showToast('修改成功')
  }catch (error) {
    console.error('修改用户名失败:', error)
    showToast('修改失败')
  }
}

// 显示昵称修改弹窗
const showNicknameDialog = () => {
  tempNickname.value = userInfo.value.nickname
  nicknameDialogVisible.value = true
}
// 确认修改昵称
const handleNicknameConfirm = async () => {
  if (!tempNickname.value || tempNickname.value.trim() === '') {
    showToast('昵称不能为空')
    return
  }
  if (tempNickname.value.length < 2 || tempNickname.value.length > 12) {
    showToast('昵称长度为2-12位')
    return
  }
  try {
    await updateUser({ nickname: tempNickname.value })
    userInfo.value.nickname = tempNickname.value
    showToast('修改成功')
  } catch (error) {
    console.error('修改昵称失败:', error)
    showToast('修改失败')
  }
}

// 显示邮箱修改弹窗
const showEmailDialog = () => {
  tempEmail.value = userInfo.value.email
  emailDialogVisible.value = true
}

// 邮箱验证
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 确认修改邮箱
const handleEmailConfirm = async () => {
  if (!tempEmail.value || tempEmail.value.trim() === '') {
    showToast('邮箱不能为空')
    return
  }
  if (!validateEmail(tempEmail.value)) {
    showToast('请输入正确的邮箱格式')
    return
  }
  try {
    await updateUser({ email: tempEmail.value })
    userInfo.value.email = tempEmail.value
    showToast('修改成功')
  } catch (error) {
    console.error('修改邮箱失败:', error)
    showToast('修改失败')
  }
}

// 显示性别选择器
const showGenderPicker = () => {
  genderPickerVisible.value = true
}

// 选择性别
const onGenderSelect = async (action) => {
  if (action.name === '取消') {
    genderPickerVisible.value = false
    return
  }
  try {
    await updateUser({ gender: action.name })
    userInfo.value.gender = action.name
    showToast('修改成功')
    genderPickerVisible.value = false
  } catch (error) {
    console.error('修改性别失败:', error)
    showToast('修改失败')
  }
}

// 点击头像
const handleAvatarClick = () => {
  avatarPickerVisible.value = true
}

// 选择头像操作
const onAvatarSelect = (action) => {
  if (action.name === '取消') {
    avatarPickerVisible.value = false
    return
  }
  
  // 触发文件选择（拍照和相册都用这个）
  fileInput.value.click()
  avatarPickerVisible.value = false
}

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  // 验证文件大小（不超过5MB）
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB')
    return
  }
  try {
    showToast('上传中...')
    const formData = new FormData()
    formData.append('image', file)  // 参数名改为image，与后端一致
    const result = await uploadImageApi(formData)
    console.log('上传结果:', result)
    if (result && result.url) {
      // 更新用户头像
      await updateUser({ avatar: result.url })
      userInfo.value.avatar = result.url
      showToast('头像更新成功')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    showToast('上传失败，请重试')
  } finally {
    // 清空input，允许选择相同文件
    event.target.value = ''
  }
}

// 显示修改密码弹窗
const showPasswordDialog = () => {
  // 清空输入框
  newPassword.value = ''
  confirmPassword.value = ''
  passwordDialogVisible.value = true
}

// 密码弹窗关闭前的回调
const handlePasswordDialogClose = (action) => {
  if (action === 'confirm') {
    // 点击确定时不关闭，由handleChangePassword处理
    return false
  }
  // 点击取消或遮罩时关闭
  return true
}

// 修改密码
const handleChangePassword = async () => {
  if (!newPassword.value || newPassword.value.trim() === '') {
    showToast('请输入新密码')
    return
  }
  
  if (!confirmPassword.value || confirmPassword.value.trim() === '') {
    showToast('请再次输入新密码')
    return
  }
  
  if (newPassword.value.length < 6) {
    showToast('新密码长度至少为6位')
    return
  }
  
  if (newPassword.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致')
    return
  }

  try {
    passwordLoading.value = true
    
    // 调用resetAccount接口修改密码
    await resetAccount({
      username: userInfo.value.username,
      password: newPassword.value
    })
    
    // 修改成功后关闭弹窗
    passwordDialogVisible.value = false
    showToast('密码修改成功，请重新登录')
    
    // 清空密码输入框
    newPassword.value = ''
    confirmPassword.value = ''
    
    // 延迟1秒后退出登录
    setTimeout(() => {
      handleLogout()
    }, 1000)
  } catch (error) {
    console.error('修改密码失败:', error)
    showToast(error.message || '修改密码失败，请稍后重试')
    // 发生错误时不关闭弹窗，让用户可以重试
  } finally {
    passwordLoading.value = false
  }
}

// 个人信息浏览及导出
const handleExportInfo = () => {
  router.push({ name: 'mineInformation' })
}

// 申请注销账号
const handleDeleteAccount = () => {
  router.push({ name: 'revoked' })
}

// 退出登录
const handleLogout = async () => {
  try {
    await showConfirmDialog({
      title: '退出登录',
      message: '确定要退出登录吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      confirmButtonColor: '#FF6B6B',
    })
    // 用户确认退出
    removeToken()
    // 清除用户store中的数据
    if (userStore && userStore.logout) {
      userStore.logout()
    }
    showToast('已退出登录')
    // 跳转到登录页
    router.push({ name: 'login' })
  } catch (error) {
    // 用户取消退出，不做任何操作
    console.log('用户取消退出登录')
  }
}
// 返回上一页
const goBack = () => {
  router.back()
}
// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang='scss' scoped>
.mine-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;

  :deep(.van-nav-bar) {
    .van-nav-bar__title {
      color: #333;
      font-weight: bold;
    }
    
    // 返回箭头样式
    .van-nav-bar__arrow {
      color: #333;           /* 箭头颜色 */
      font-size: 18px;       /* 箭头大小 */
      font-weight: 600;      /* 箭头粗细 */
    }
  }
  
  :deep(.avatar-cell) {
    min-height: 80px;
    padding: 10px 16px;
    
    .van-cell__title {
      display: flex;
      align-items: center;
    }
    
    .van-cell__value {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .van-cell__right-icon {
      padding-top: 15px;
      margin-left: 8px;
    }
  }

  .avatar-image {
    position: absolute;
    width: 60px;
    height: 60px;
    right: 0;
    flex-shrink: 0; // 禁止图片宽度自适应
  }

  .readonly-text {
    color: #999;
  }

  // 功能列表
  .function-list {
    margin-top: 10px;
    background-color: #fff;
    border-radius: 6px;
    overflow: hidden;
    
    :deep(.van-cell) {
      .van-icon {
        color: #FFD847;
      }
    }

    .warning-text {
      color: #ff6666;
      font-size: 12px;
    }
  }

  
  // 弹窗样式
  :deep(.van-dialog) {
    .van-field {
      padding: 10px 16px;
    }
  }

  // 密码弹窗内容
  .password-dialog-content {
    padding: 20px 0;
  }
}
</style>